﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Pariveda.DataAccess35.Business
{
    /// <summary>
    /// Utility class for serialization of LINQ Entities using WCF Serialization
    /// </summary>
    public static class SerializerUtil
    {

        /// <summary>
        /// Serializes the specified entity.
        /// </summary>
        /// <param name="entity">The entity to serialize</param>
        /// <returns></returns>
        public static string Serialize<T>(this T entity)
        {
            StringWriter writer = new StringWriter();
            XmlTextWriter xmlWriter = new XmlTextWriter(writer);
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(xmlWriter, entity);
            return writer.ToString();
        }

        /// <summary>
        /// Deserializes the specified XML to the specified type
        /// </summary>
        /// <typeparam name="T">Type to deserialize to</typeparam>
        /// <param name="xml">The XML of the object graph</param>
        /// <returns></returns>
        public static T Deserialize<T>(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            StringReader reader = new StringReader(xml);
            XmlTextReader xmlReader = new XmlTextReader(reader);
            return (T)serializer.ReadObject(xmlReader);
        }

        /// <summary>
        /// Clones the specified customer by serializing and deserializing the entity
        /// </summary>
        /// <param name="customer">The entity to clone</param>
        /// <returns></returns>
        public static T Clone<T>(this T entity)
        {
            return Deserialize<T>(Serialize(entity));
        }
    }
}
